package com.jf.concurrent.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static java.lang.System.out;

/**
 * Condition 的 await 和 signal 与 wait 和 notify 一样，也有两个前提
 * 1、必须使用同意把锁
 * 2、notify必须在wait之后
 *
 * @author Junfeng
 */
public class ConditionAwaitSignal {

    public static void main(String[] arg) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        new Thread(() -> {
            lock.lock();
            try {
                out.println(Thread.currentThread().getName() + " 线程进入等待");
                condition.await();
                out.println(Thread.currentThread().getName() + " 线程被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "AA").start();

        new Thread(() -> {
            lock.lock();
            try {
                condition.signal();
                out.println(Thread.currentThread().getName() + " 线程唤醒AA");
            } finally {
                lock.unlock();
            }
        }, "BB").start();

    }
}
